package com.cennavi.minemap.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;

import com.cennavi.minemap.bean.SoluLogBean;

@Component
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class })
public class ReportDao extends AbstractDao {

	public int insert(final SoluLogBean soluLogBean) {
		jdbcTemplate.setDataSource(pgDataSource);
		final String sql = "INSERT INTO mm_solu_log(" + "userId, soluId, isPublish, ip, dateTime) "
				+ "VALUES (?, ?, ?, ?, ?)";
		KeyHolder keyHolder = new GeneratedKeyHolder();
		jdbcTemplate.update(new PreparedStatementCreator() {
			public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
				PreparedStatement ps = conn.prepareStatement(sql,
						new String[] { "id" });
				ps.setInt(1, soluLogBean.getUserId());
				ps.setInt(2, soluLogBean.getSoluId());
				ps.setInt(3, soluLogBean.getIsPublish());
				ps.setString(4, soluLogBean.getIp());
				ps.setString(5, soluLogBean.getDateTime());
				return ps;
			}
		}, keyHolder);
		return keyHolder.getKey().intValue();
	}

	public List<Map<String, Object>> queryReport(String sql, Object[] object) {
		jdbcTemplate.setDataSource(pgDataSource);
		List<Map<String, Object>> list = jdbcTemplate.query(sql, object,
				new ResultSetExtractor<List<Map<String, Object>>>() {
					@Override
					public List<Map<String, Object>> extractData(ResultSet rs)
							throws SQLException, DataAccessException {
						ResultSetMetaData metaData = rs.getMetaData();
						int count = metaData.getColumnCount();
						List<Map<String, Object>> l = new ArrayList<>();

						while(rs.next()){
							Map<String, Object> map = new HashMap<>();
							for (int i = 0; i < count; i++) {
								String fieldName = metaData.getColumnName(i + 1).toLowerCase();
								//int type = metaData.getColumnType(i + 1);
								//String typeName = metaData.getColumnTypeName(i + 1).toLowerCase();
								//System.out.println(fieldName + " : " + type + " : " + typeName);
								map.put(fieldName, rs.getObject(fieldName));
							}
							l.add(map);
						}
						return l;
					}
				});

		return list;
	}
}
